const _ = require('lodash');
const moment = require('moment');
const prefix = '/api/iresearch';

module.exports = (app) => {
    const {router, middleware} = app;

    //搜索分类
    router.get(prefix + '/category', middleware.api(2), async ctx => {
        const {DailyPlatformCategory, Platform, DailyCategory} = ctx.app.model;
        const where = {};
        let {id, search} = ctx.query;
        if (!_.isEmpty(search))
            where.name = {[ctx.app.Sequelize.Op.like]: '%' + search + '%'};
        else if (!_.isEmpty(id))
            where.id = {[ctx.app.Sequelize.Op.in]: id.split(',')};
        else
            return ctx.body = [];
        let result;
        if (id) {
            result = await DailyPlatformCategory.findAll({
                where,
                include: [{model: DailyCategory}],
            });
        } else {
            result = await DailyPlatformCategory.findAll({
                include: [
                    {model: Platform, where: {platform: {[app.Sequelize.Op.not]: null}}},
                    {model: DailyCategory, order: [['name', 'asc']], where},
                ]
            });
            result = result.map(item => {
                return {id: item.id, category: item.daily_category, platform: item.platform};
            });
        }
        ctx.body = result;
    });

    //根据开始日期和结束，检索每日分类的数据
    router.get(prefix + '/data/:category/:start/:end', middleware.api(2), async ctx => {
        let {category, start, end} = ctx.params;
        let platforms = await ctx.app.model.Platform.findAll({where: {platform: {[app.Sequelize.Op.ne]: null}}});
        platforms = _.keyBy(platforms, 'id');
        const res = await ctx.app.model.DailyCategoryData.findAll({
            order: [['created_at', 'asc'], ['platform_id', 'asc'],],
            where: {
                created_at: {[ctx.app.Sequelize.Op.between]: [start, end]},
                daily_category_id: category
            },
        });
        const final = {table: {}, chart: {}};
        start = moment(start);
        end = moment(end);

        //按 日期 组合
        const dateData = _.groupBy(res, 'created_at');
        const legend = {data: _.map(platforms, 'name')};
        //日期
        const date = [];
        //5个数据项目
        const watch = {}, _new = {}, open = {}, gift = {}, active = {};
        //按平台初始化5个数据项目
        _.each(platforms, p => {
            watch[p.id] = {
                name: p.name,
                type: 'line',
                data: [],
            };
            _new[p.id] = {
                name: p.name,
                type: 'line',
                data: [],
            };
            open[p.id] = {
                name: p.name,
                type: 'line',
                data: [],
            };
            gift[p.id] = {
                name: p.name,
                type: 'line',
                data: [],
            };
            active[p.id] = {
                name: p.name,
                type: 'line',
                data: [],
            };
        });

        let tableData;

        {//数据表 逻辑 区别，以日期为x轴，平台为y轴
            /*
            tableData = {};
            let diff = end.diff(start, 'day');
            while (diff >= 0) {
                const created_at = start.format('YYYY-MM-DD');
                const dateString = start.format('MM月DD日');
                const data = dateData[created_at];

                if (data) {
                    // console.log(created_at, '有数据');
                    data.forEach(d => {
                        const id = d.platform_id;
                        watch[id].data.push(d.watch);
                        _new[id].data.push(d._new);
                        open[id].data.push(d.open);
                        gift[id].data.push(d.gift);
                        active[id].data.push(d.active);
                        if (!tableData[id])
                            tableData[id] = {
                                platform: platforms[id].name, [dateString]: {
                                    watch: d.watch, _new: d._new, open: d.open, gift: d.gift, active: d.active
                                }
                            };
                        else
                            tableData[id][dateString] = {
                                watch: d.watch, _new: d._new, open: d.open, gift: d.gift, active: d.active,
                            };
                    });
                }
                else {
                    _.each(platforms, p => {
                        const id = p.id;
                        watch[id].data.push(0);
                        _new[id].data.push(0);
                        open[id].data.push(0);
                        gift[id].data.push(0);
                        active[id].data.push(0);
                        if (!tableData[id])
                            tableData[id] = {
                                platform: p.name, [dateString]: {watch: 0, _new: 0, open: 0, gift: 0, active: 0}
                            };
                        else
                            tableData[id][dateString] = {
                                watch: 0, _new: 0, open: 0, gift: 0, active: 0,
                            };
                    });
                }
                date.push(dateString);
                start.add(1, 'day');
                diff = end.diff(start, 'day');
            }
            final.table.data = Object.values(tableData);
            final.table.date = date;*/
        }
        {//数据表 逻辑 区别，以日期为y轴，平台为x轴
            tableData = [];
            let diff = end.diff(start, 'day');
            while (diff >= 0) {
                const created_at = start.format('YYYY-MM-DD');
                const dateString = start.format('MM月DD日');
                let row = {date: dateString, watch: {}, _new: {}, active: {}, open: {}, gift: {}};

                tableData.push(row);
                const data = dateData[created_at];
                if (data) {
                    // console.log(created_at, '有数据');
                    _.each(platforms, p => {
                        const id = p.id;
                        let d = _.find(data, {platform_id: id});
                        let watchData = 0, _newData = 0, openData = 0, giftData = 0, activeData = 0;
                        if (d) {
                            watchData = d.watch;
                            _newData = d._new;
                            openData = d.open;
                            giftData = d.gift;
                            activeData = d.active;
                        }
                        watch[id].data.push(watchData);
                        _new[id].data.push(_newData);
                        open[id].data.push(openData);
                        gift[id].data.push(giftData);
                        active[id].data.push(activeData);
                        row.watch[id] = watchData;
                        row._new[id] = _newData;
                        row.open[id] = openData;
                        row.gift[id] = giftData;
                        row.active[id] = activeData;
                    });
                } else {
                    _.each(platforms, p => {
                        const id = p.id;
                        watch[id].data.push(0);
                        _new[id].data.push(0);
                        open[id].data.push(0);
                        gift[id].data.push(0);
                        active[id].data.push(0);
                        row.watch[id] = 0;
                        row._new[id] = 0;
                        row.open[id] = 0;
                        row.gift[id] = 0;
                        row.active[id] = 0;
                    });
                }


                date.push(dateString);
                start.add(1, 'day');
                diff = end.diff(start, 'day');
            }
            final.table.data = tableData;
            final.table.date = date;
        }

        final.chart.watch = Object.values(watch);
        final.chart.active = Object.values(active);
        final.chart._new = Object.values(_new);
        final.chart.gift = Object.values(gift);
        final.chart.open = Object.values(open);
        final.chart.legend = legend;
        final.chart.xAxis = {data: date};
        ctx.body = final;
    });


    /**手动重新抓取数据*/
    router.get(prefix + '/data/:platform_id/:date', middleware.api(2), async ctx => {
        let platform = await app.model.Platform.findOne({
            raw: true,
            where: {
                id: ctx.params.platform_id,
                platform: {[app.Sequelize.Op.not]: null}
            }
        });
        if (!platform)
            return ctx.helper.error('不存在的平台');

        ctx.body = await ctx.service.iresearch.get(platform, ctx.params.date);
    });
};